package com.hitrust.gs.util;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;
import framework.core.LogWriter;

/**
 * 
 * @author frank.yu
 *
 */
public class ResponseUtils {

	//header 常量定义
	private static final String ENCODING_DEFAULT = "UTF-8";

	// 绕过jsp/freemaker直接输出文本的函数 //

	/**
	 * 直接输出内容的简便函数.

	 * eg.
	 * render("text/plain", "hello", "encoding:GBK");
	 * render("text/plain", "hello", "no-cache:false");
	 * render("text/plain", "hello", "encoding:GBK", "no-cache:false");
	 * 
	 */
	public static void render(HttpServletResponse response,final String contentType, final String content) {
		try {
			//分析headers参数
			String encoding = ENCODING_DEFAULT;

			//设置headers参数
			String fullContentType = contentType + ";charset=" + encoding;
			response.setContentType(fullContentType);
			
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			

			response.getWriter().write(content);
			response.getWriter().flush();

		} catch (IOException e) {
			LogWriter.error(e.getMessage(), e);
		}
	}

	/**
	 * 直接输出文本.
	 * @see #render(String, String, String...)
	 */
	public static void renderText(HttpServletResponse response,final String text) {
		render(response,"text/plain", text);
	}

	/**
	 * 直接输出HTML.
	 * @see #render(String, String, String...)
	 */
	public static void renderHtml(HttpServletResponse response,final String html) {
		render(response,"text/html", html);
	}

	/**
	 * 直接输出XML.
	 * @see #render(String, String, String...)
	 */
	public static void renderXml(HttpServletResponse response,final String xml) {
		render(response,"text/xml", xml);
	}

	/**
	 * 直接输出JSON.
	 * 
	 * @param string json字符串.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(HttpServletResponse response,final String jsonString) {
		render(response,"application/json", jsonString);
	}

}
